package com.mymongo;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.LinkedHashMap;
import java.util.Map;
import org.bson.Document;

public class MongoMain {

    public static void main(String[] args) {
        // 1 connect host
        MongoClient client = new MongoClient("66.42.34.30");
        // 2 chose database
        MongoDatabase spitdb = client.getDatabase("spitdb");
        // 3 chose collection
        MongoCollection<Document> spitCollection = spitdb.getCollection("spit");

        // query all
        FindIterable<Document> documents = spitCollection.find();
        long total = spitCollection.count();
        System.out.println("============1.0、condition query============ " + total);
        for (Document doc : documents) {
            print(doc);
        }

        // query common condition
        FindIterable<Document> visits = spitCollection.find(new BasicDBObject("visits", 111));
        System.out.println("============1.1、condition query============");
        for (Document doc : visits) {
            print(doc);
        }

        // query greater than 1000
        BasicDBObject gtQuery = new BasicDBObject("$gt",1000);
        BasicDBObject bson = new BasicDBObject("visits",gtQuery);
        FindIterable<Document> gt1000 = spitCollection.find(bson);
        total = spitCollection.count(bson);
        System.out.println("============1.2、condition query============ " + total);
        for (Document doc : gt1000) {
            print(doc);
        }

        // insert
//        Map<String, Object> values = new LinkedHashMap<>();
//        values.put("_id", "888");
//        values.put("content", "今天不喝娃哈哈");
//        values.put("userid", "10086");
//        values.put("nickname", "张晓明");
//        values.put("visits", 888);
//        Document dest = new Document(values);
//        spitCollection.insertOne(dest);
        client.close();
    }

    private static void print(Document doc) {
        System.out.println("id = " + doc.getString("_id"));
        System.out.println("content = " + doc.getString("content"));
        System.out.println("userid = " + doc.getString("userid"));
        System.out.println("nickname = " + doc.getString("nickname"));
        System.out.println("visits = " + doc.getInteger("visits"));
    }

}
